const { stuModel, orgInfoModel } = require('../../model/index');
const tokens = require('../../services/tokenService');
const { SUCCESS, STU_LOGIN_FAIL, STU_LOGIN_NULL } = require('../message');
const { getResultToObjectComplete } = require('../../services/utils');

module.exports = {
  login: async (req, res) => {
    const { learn_number, password } = req.body;

    if (!learn_number || !password) {
      return res.send({
        status: -1,
        ...STU_LOGIN_NULL
      });
    }

    // TODO 用户密码加密
    const student = await stuModel.findByRelation([
        'id',
        'learn_number',
        'org',
        'name'
    ], {
      learn_number: learn_number,
      password: password
    }, {
      model: orgInfoModel.getModel(),
      attributes: ['icon']
    });

    if (student[0]) {
      const list = getResultToObjectComplete(student,'org_info',['icon']);
      const { id, learn_number, org, name, icon } = list[0];
      const token = tokens.createToken({id: id, learn_number: learn_number, org: org, name: name, icon: icon},24 * 3600 * 30);
      return res.send({
        status: 0,
        code: 20000,
        token: token,
        data: {
          learn_number: learn_number,
          name: name
        }
      })
    } else {
      return res.send(STU_LOGIN_FAIL)
    }
  },
  info: async (req, res) => {
    const org_info = await orgInfoModel.findOne(['logo', 'name'], { id: req.decode.org});
    return res.send({
      code: 20000,
      data: {
        ...req.decode,
        logo: org_info.logo,
        org_name: org_info.name
      }
    })
  },
  logout: function (req, res) {
    return res.send({
      code: 20000,
      data: 'success'
    });
  }
};
